/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mongoosehome.web.onlinemall.product.action;

import com.mongoosehome.web.base.BaseActon;
import com.mongoosehome.web.common.domain.TProducts;
import com.mongoosehome.web.onlinemall.product.service.ProductService;
import com.mongoosehome.web.enumcommon.DbSortTypeEnum;
import com.mongoosehome.web.enumcommon.PageSizeEnum;
import com.mongoosehome.web.util.BaseResource;
import com.mongoosehome.web.util.PageInfo;
import com.mongoosehome.web.util.RequestUtils;
import java.io.File;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

/**
 *
 * @author Administrator
 */
public class ProductAction extends BaseActon {

    private static final long serialVersionUID = 1L;
    private Logger logger = LogManager.getLogger(ProductAction.class);
    private ProductService productService;
    private TProducts tProducts;
    private String tabid;    //需要刷新的tabid,针对dwz的特殊要求。

    /**
     * @param productService the productService to set
     */
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    /**
     * 在线商场商品的列表。
     *
     * @return
     */
    @Override
    public String execute() {
        //获取参数，前台传过来的参数。
        int pageNum = RequestUtils.getIntParameter(request, "pageNum", 1);
        int numPerPage = RequestUtils.getIntParameter(request, "numPerPage", PageSizeEnum.PAGE_SIZE.getValue());

        //列出所有商品的信息。在前台界面显示。       
        PageInfo pageInfo = this.productService.getProductsList(pageNum, numPerPage, "productId", DbSortTypeEnum.DESC.getValue());
        request.setAttribute("productPageInfo", pageInfo);        
        request.setAttribute("imagePath", BaseResource.getPathValue("product.upload.path","/", true, true));
        return SUCCESS;
    }

    public String add() {
        request.setAttribute("tabid", this.tabid);
        return "add";
    }

    /**
     * 添加产品图片。
     *
     * @return
     */
    public String addImages() {
        int pid = RequestUtils.getIntParameter(request, "pid", 0);
        //查询该商品。
        TProducts tProductsTemp = this.productService.getProducts(pid);
        request.setAttribute("p", tProductsTemp);
        return "addImages";
    }

    /**
     * 处理提交图片请求。
     *
     * @return
     * @throws Exception  
     *
     */
    public String addImagesSubmit() throws Exception {
        TProducts products = this.productService.getProducts(this.tProducts.getProductId());
        //移动文件。
        String rootPath = ServletActionContext.getServletContext().getRealPath("/");
        String filePath = BaseResource.getPathValue("product.upload.path",File.separator,false,true);
        String filePathTemp = BaseResource.getPathValue("product.upload.path.temp",File.separator,false,true);       

        //创建目录
        File createPath = new File(rootPath + filePath);
        if (!createPath.exists()) {
            createPath.mkdirs();
        }
        //移动文件。
        String[] photoArray = this.tProducts.getPhotoTurn().split(",");
        for (int i = 0; i < photoArray.length; i++) {
            File fileTemp = new File(rootPath + filePathTemp + photoArray[i]);
            FileUtils.copyFileToDirectory(fileTemp, createPath);
            fileTemp.delete();
        }
        products.setPhotoTurn(this.tProducts.getPhotoTurn());
        //默认第一个作为显示。
        products.setPhoto(photoArray[0]);
        this.productService.updateProducts(products);
        JSONObject obj = new JSONObject();
        obj.put("statusCode", 200);
        obj.put("message", "文件保存成功!");
        obj.put("callbackType", "closeCurrent");
        this.responseWriteJson(obj.toString());
        return null;
    }

    /**
     * 更新界面。
     * @return 
     */
    public String update(){
        int pid = RequestUtils.getIntParameter(request, "pid", 0);
        request.setAttribute("tabid", this.tabid);
        request.setAttribute("product",this.productService.getProducts(pid));        
        return "update";
    }

    /**
     * 处理商品信息更新操作。
     * @return
     * @throws Exception 
     */
    public String updateSubmit() throws  Exception{       
        TProducts tProductsTemp = this.productService.getProducts(this.tProducts.getProductId());
        tProductsTemp.setProductName(this.tProducts.getProductName());
        tProductsTemp.setPrice(this.tProducts.getPrice());
        this.productService.updateProducts(tProductsTemp);
        JSONObject obj = new JSONObject();
        obj.put("statusCode", 200);
        obj.put("message", "商品修改成功!");
        obj.put("navTabId", this.tabid);
        obj.put("callbackType", "closeCurrent");
        this.responseWriteJson(obj.toString());
        return null;
    }
    
    /**
     * 更新图片。
     * @return 
     */
    public String updateImages(){
        int pid = RequestUtils.getIntParameter(request, "pid", 0);
        request.setAttribute("tabid", this.tabid);
        request.setAttribute("p",this.productService.getProducts(pid));
        request.setAttribute("imagePath", BaseResource.getPathValue("product.upload.path","/", true, true));
        return "updateImages";
    }
    
    
    /**
     * 更新图片，新增加一些图片。
     * @return 
     */
    public String updateImagesSubmit() throws Exception{
        TProducts products = this.productService.getProducts(this.tProducts.getProductId());
        //移动文件。
        String rootPath = ServletActionContext.getServletContext().getRealPath("/");
        String filePath = BaseResource.getPathValue("product.upload.path",File.separator,false,true);
        String filePathTemp = BaseResource.getPathValue("product.upload.path.temp",File.separator,false,true);       

        //创建目录
        File createPath = new File(rootPath + filePath);
        if (!createPath.exists()) {
            createPath.mkdirs();
        }
        //移动文件。
        String[] photoArray = this.tProducts.getPhotoTurn().split(",");
        for (int i = 0; i < photoArray.length; i++) {
            File fileTemp = new File(rootPath + filePathTemp + photoArray[i]);
            FileUtils.copyFileToDirectory(fileTemp, createPath);
            fileTemp.delete();
        }
        if (products.getPhotoTurn()!=null && products.getPhotoTurn().length()>0){
            products.setPhotoTurn(products.getPhotoTurn()+","+this.tProducts.getPhotoTurn());
        }else{
            products.setPhotoTurn(this.tProducts.getPhotoTurn());
        }        
        this.productService.updateProducts(products);
        JSONObject obj = new JSONObject();
        obj.put("statusCode", 200);
        obj.put("message", "图片增加成功!");
        obj.put("navTabId", this.tabid);
        obj.put("callbackType", "");
        this.responseWriteJson(obj.toString());
        return null;
    }
    
    
    /**
     * 删除轮转图片。
     * @return
     * @throws Exception  
     */
    public String deleteTurnImages()throws Exception{
        String  picid = RequestUtils.getStringParameter(request, "picid", "");
        int  pid = RequestUtils.getIntParameter(request, "pid", 0);
        TProducts products = this.productService.getProducts(pid);
        
        String regExe = "(((,)?"+picid+")|("+picid+"(,)?))";
        String photoTurn = products.getPhotoTurn();
        products.setPhotoTurn(photoTurn.replaceAll(regExe, ""));
        if (products.getPhoto().equals(picid)){
            products.setPhoto(products.getPhotoTurn().split(",")[0]);
        }
        this.productService.saveProducts(products);
        //删除对应的文件。
        String rootPath = ServletActionContext.getServletContext().getRealPath("/");
        String filePath = BaseResource.getPathValue("product.upload.path",File.separator,false,true);
        File file = new File(rootPath+filePath+picid);
        if (file.exists()){
            file.delete();
        }
        
        JSONObject obj = new JSONObject();
        obj.put("statusCode", 200);
        obj.put("message", "图片删除成功!");
        obj.put("navTabId", this.tabid);
        obj.put("callbackType", "");
        this.responseWriteJson(obj.toString());
        return null;
    }
    
    /**
     * 设置封面图片。
     * @return
     * @throws Exception  
     */
    public String resetCoverImage() throws Exception{
        String  picid = RequestUtils.getStringParameter(request, "picid", "");
        int  pid = RequestUtils.getIntParameter(request, "pid", 0);
        TProducts products = this.productService.getProducts(pid);
        products.setPhoto(picid);
        this.productService.saveProducts(products);
        JSONObject obj = new JSONObject();
        obj.put("statusCode", 200);
        obj.put("message", "封面图片设置成功!");
        obj.put("navTabId", this.tabid);
        obj.put("callbackType", "");
        this.responseWriteJson(obj.toString());
        return null;
    }
    
    
    public String delete() {
        return "delete";
    }

    /**
     * 处理添加产品。返回json格式。
     *
     * @return
     * @throws Exception
     */
    public String addProduct() throws Exception {
        if (!this.productService.isProducts(this.tProducts.getProductName())) {
            this.tProducts.setCreateTime(new Date());
            this.productService.saveProducts(tProducts);
            JSONObject obj = new JSONObject();
            obj.put("statusCode", 200);
            obj.put("message", "操作成功!");
            obj.put("navTabId", this.tabid);
            obj.put("rel", "");
            obj.put("callbackType", "forward");
            obj.put("forwardUrl", "productList!addImages.htm?pid=" + this.tProducts.getProductId());
            obj.put("confirmMsg", "");
            this.responseWriteJson(obj.toString());
        } else {
            JSONObject obj = new JSONObject();
            obj.put("statusCode", 300);
            obj.put("message", "操作失败，已存在该商品名称!");
            this.responseWriteJson(obj.toString());
        }
        return null;
    }

    /**
     * @return the tProducts
     */
    public TProducts gettProducts() {
        return tProducts;
    }

    /**
     * @param tProducts the tProducts to set
     */
    public void settProducts(TProducts tProducts) {
        this.tProducts = tProducts;
    }

    /**
     * @param tabid the tabid to set
     */
    public void setTabid(String tabid) {
        this.tabid = tabid;
    }
}
